package com.common;

import com.merge.FileWrite;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class FileWriterUtils {

    public static Map<String, FileWriter> fileWriterMap = new HashMap<String, FileWriter>();

    /**
     * 根据path路径获取fileWriter对象
     * @param path
     * @return
     * @throws IOException
     */
    public static FileWriter getFileWriter(String path) throws IOException {
        if (!fileWriterMap.containsKey(path)) {
            FileWriter fileWriter = new FileWriter(path, true);
            fileWriterMap.put(path, fileWriter);
        }
        return fileWriterMap.get(path);
    }

    /**
     * 按行写数据
     * @param path
     * @param content
     */
    public static void writeLine(String path, String content) {
        try {
            FileWriter fileWriter = getFileWriter(path);
            fileWriter.write(content+ "\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeLine(String path, int number) {
        String content = String.valueOf(number);
        writeLine(path, content);
    }

    public static void flush(String path) {
        try {
            FileWriter fileWrite = getFileWriter(path);
            fileWrite.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 关闭io流
     * @param path
     * @throws IOException
     */
    public static void close(String path) throws IOException {
        if (fileWriterMap.containsKey(path)) {
            FileWriter fileWriter = getFileWriter(path);
            fileWriter.flush();
            fileWriter.close();
        }
    }

    public static void close() throws IOException {
         Set<String> paths = fileWriterMap.keySet();
         for(String path : paths) {
             close(path);
         }
    }

    public static void main(String[] args) {
        String path = "E:\\document\\io_demo\\filewriter_demo.txt";
        for (int i = 11; i <20; i++) {
            writeLine(path, i + "");
        }
        try {
            FileWriter fileWriter = getFileWriter(path);
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
